from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
import json
from autoserver import settings
from django.conf import settings, global_settings
from django.views.decorators.csrf import csrf_exempt


# Create your views here.
@csrf_exempt
def asset(request):
	if request.method == 'POST':
		print(request.POST)  # k1=ens333&k2=ens333
		print(request.body)  # 原始数据
		ret = json.loads(request.body.decode('utf-8'))
		print(ret, type(ret))
		return HttpResponse('接受到了')
	if request.method == 'GET':
		host_list = [i for i in range(1, 1000)]
		return JsonResponse(host_list, safe=False)


# 写API使用CBV
from django.views import View
from django.utils.decorators import method_decorator

# @method_decorator(csrf_exempt, name='dispatch')
# class Asset(View):
#
# 	def get(self, request):
# 		print('get')
# 		host_list = [i for i in range(1, 100)]
# 		return JsonResponse(host_list, safe=False)
#
# 	def post(self, request):
# 		print('post')
# 		ret = json.loads(request.body.decode('utf-8'))
# 		return HttpResponse('接受到了')

from rest_framework.views import APIView
from rest_framework.response import Response
from repository import models
from api.service import process_basic, process_disk, process_memory, process_nic
from django.conf import settings

def gen_key(ctime):
	key = "{}|{}".format(settings.AUTH_KEY, ctime)
	md5 = hashlib.md5()
	md5.update(key.encode('utf-8'))
	return md5.hexdigest()

SIGN_RECORD = {}

class AuthAPI(APIView):

	def dispatch(self, request, *args, **kwargs):
		key = request.GET.get('key')
		ctime = request.GET.get('ctime')
		now = time.time()

		sign = gen_key(ctime)
		ret = {'status': True, 'msg': '嘿嘿嘿'}

		if float(now) - float(ctime) > 2:
			# 时间长久失效
			ret['status'] = False
			ret['msg'] = '你跑的太慢了'
			return Response(ret)
		elif key in SIGN_RECORD:
			# key已经使用过了
			ret['status'] = False
			ret['msg'] = 'key已被使用'
			return Response(ret)

		elif key != sign:
			ret['status'] = False
			ret['msg'] = '校验不通过'
			return Response(ret)
		else:
			# 通过校验
			SIGN_RECORD[key] = now
			# 执行父类的dispatch()
			return super().dispatch(request, *args, **kwargs)


class Asset(AuthAPI):

	def get(self, request):
		print('get')
		host_list = [i for i in range(1, 100)]
		# return JsonResponse(host_list, safe=False)
		return Response(host_list)

	def post(self, request):
		print('post')
		# ret = json.loads(request.body.decode('utf-8'))

		response = {'status': True, 'hostname': None, 'error': None}
		info = request.data  # 自动反序列化

		info_type = info.get('type')
		if info_type == 'create':
			# 新增资产
			# ############   新增主机  ############
			server_dict = {}

			basic_info = info['basic']['data']
			board_info = info['board']['data']
			cpu_info = info['cpu']['data']
			server_dict.update(basic_info)
			server_dict.update(board_info)
			server_dict.update(cpu_info)

			server = models.Server.objects.create(**server_dict)

			# ############   新增硬盘  ############
			disk_info = info['disk']['data']
			dick_obj_list = []
			for i in disk_info.values():
				i['server'] = server
				# i['server_id'] = server.pk
				dick_obj_list.append(models.Disk(**i))  # 内存中的对象
			models.Disk.objects.bulk_create(dick_obj_list)

			# ############   新增内存  ############
			memory_info = info['memory']['data']
			memory_obj_list = []
			for i in memory_info.values():
				i['server'] = server
				# i['server_id'] = server.pk
				memory_obj_list.append(models.Memory(**i))  # 内存中的对象
			models.Memory.objects.bulk_create(memory_obj_list)

			# ############   新增网卡  ############
			nic_info = info['NIC']['data']
			nic_obj_list = []
			for name, i in nic_info.items():
				i['server'] = server
				i['name'] = name
				# i['server_id'] = server.pk
				nic_obj_list.append(models.NIC(**i))  # 内存中的对象
			models.NIC.objects.bulk_create(nic_obj_list)

		elif info_type == 'update':
			# 更新资产
			print('update')
			#   更新 主机表    cpu  主板  基本
			server = process_basic(info)
			#  ############ 硬盘变更  ############
			process_disk(info, server)
			#  ############ 内存变更  ############
			process_memory(info, server)
			#  ############ 网卡变更  ############
			process_nic(info, server)

		elif info_type == 'host_update':
			# 更新主机名 + 资产
			print('host_update')
			print(info)
			#   更新 主机表    cpu  主板  基本
			server = process_basic(info)
			#  ############ 硬盘变更  ############
			process_disk(info, server)
			#  ############ 内存变更  ############
			process_memory(info, server)
			#  ############ 网卡变更  ############
			process_nic(info, server)

		response['hostname'] = info['basic']['data']['hostname']

		return Response(response)


KEY = 'ASKJHASFBNWFP；asdf'

import time
import hashlib

ctime = time.time()

class Test(APIView):
	def post(self, request):
		key = request.GET.get('key')
		ctime = request.GET.get('ctime')
		now = time.time()

		sign = gen_key(ctime)
		ret = {'status': True, 'msg': '嘿嘿嘿'}

		if float(now) - float(ctime) > 2:
			# 时间长久失效
			ret['status'] = False
			ret['msg'] = '你跑的太慢了'

		elif key in SIGN_RECORD:
			# key已经使用过了
			ret['status'] = False
			ret['msg'] = 'key已被使用'

		elif key != sign:
			ret['status'] = False
			ret['msg'] = '校验不通过'

		else:
			SIGN_RECORD[key] = now

		return Response(ret)
